import React, { Component } from 'react';
import Grid from '@material-ui/core/Grid';
import Modal from '@material-ui/core/Modal';
import Card from '@material-ui/core/Card';
import Typography from '@material-ui/core/Typography';
import { Get, Post, PostWithSession, sleep, deepCopy, replaceAll, transList, GetAsync } from './utility';
import { CardContent } from '@material-ui/core';
import router from 'umi/router';
import { makeStyles } from '@material-ui/core/styles';
import Container from '@material-ui/core/Container';
import CardMedia from '@material-ui/core/CardMedia';
import CardActions from '@material-ui/core/CardActions';
import Button from '@material-ui/core/Button';
import CssBaseline from '@material-ui/core/CssBaseline';
import Toolbar from '@material-ui/core/Toolbar';
import AppBar from '@material-ui/core/AppBar';
import Backdrop from '@material-ui/core/Backdrop';

import { createMuiTheme, ThemeProvider } from '@material-ui/core/styles';
import orange from '@material-ui/core/colors/orange';


const theme = createMuiTheme({
  palette: {
    primary: orange,
  },
});

const Event = {};
Event.addEvents = function(target,eventType,handle){
  if(document.addEventListener){
      Event.addEvents = function(target,eventType,handle){
          target.addEventListener(eventType,handle,false);
      };
  }else{
      Event.addEvents = function(target,eventType,handle){
          target.attachEvent('on'+eventType,function(){
              handle.call(target,arguments);
          });
      };
  };
  Event.addEvents(target,eventType,handle);
};

const pageHeight = 'calc( 100vh - 93px )'
const itemPageHeight = 'calc( 100vh - 125px )'
const itemWidth = 'calc( 100vw / 8 )'

const title = "购买物品"
const NetErrMsg = "出现异常, 请联系波比"
const tableCols = 5
const picUrl = "http://120.78.174.207:6185/"

const Styles = {
  'title': {
    'fontSize': '25px',
    'fontFamily': '微软雅黑',
    'textAlign': "center",
    'marginBottom': '5px',
    color: '#283593',
  },

  'page': {
    Width: "100%",
    maxWidth: '100%',
    padding: "0 16px",
    height: pageHeight,
    'overflow': 'auto',
  },

  'itemPage': {
    Width: "100%",
    maxWidth: '100%',
    padding: "0 16px",
    height: itemPageHeight,
    'overflow': 'auto',
  },

  'confirmPage': {
    Width: "30%",
    maxWidth: '30%',
    padding: "0 16px",
    height: "30%",
    maxHeight: "100px",
    margin: "100px auto",
    background: 'rgb(180, 180, 255)',
  },

  'grid': {
    Width: "100%",
    maxWidth: '100%',
    // 'overflow': 'auto',
  },

  'info': {
    'fontSize': '18px',
    'fontFamily': '微软雅黑',
    'textAlign': "left",
    'marginBottom': '5px',
    color: 'rgb(0, 0, 0)',
  },

  'sendBtn': {
    'fontSize': '14px',
    'fontFamily': '微软雅黑',
    'align': 'right',
    'verticalAlign': 'middle',
    color: 'rgb(255, 255, 255)',
    background: '#283593',
    'borderRadius': '8px',
    border: '0px',
    outline: 'none',
  },

  'item': {
    width: itemWidth,
  },
};

const useStyles = makeStyles(theme => ({
  icon: {
    marginRight: theme.spacing(2),
  },
  heroContent: {
    backgroundColor: theme.palette.background.paper,
    padding: theme.spacing(8, 0, 6),
  },
  heroButtons: {
    marginTop: theme.spacing(4),
  },
  cardGrid: {
    paddingTop: theme.spacing(2),
    paddingBottom: theme.spacing(8),
    'overflow': 'auto',
    height: pageHeight,
  },
  card: {
    height: '100%',
    display: 'flex',
    flexDirection: 'column',
  },
  cardMedia: {
    paddingTop: '56.25%', // 16:9
  },
  cardContent: {
    flexGrow: 1,
  },
  footer: {
    backgroundColor: theme.palette.background.paper,
    padding: theme.spacing(6),
  },
  modal: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
  },
  paper: {
    backgroundColor: theme.palette.background.paper,
    border: '2px solid #000',
    boxShadow: theme.shadows[5],
    padding: theme.spacing(2, 4, 3),
  },
}));

function MyCardMedia(props) {
  const { paddingTop, ...other } = props;
  const classes = useStyles(props);
  return <CardMedia className={classes.cardMedia} {...other} />;
}

function MyCard(props) {
  const { ...other } = props;
  const classes = useStyles(props);
  return <Card className={classes.Card} {...other} />;
}

function MyCardGrid(props) {
  const { ...other } = props;
  const classes = useStyles(props);
  return <Container className={classes.cardGrid} {...other} />;
}

function MyCardContent(props) {
  const { ...other } = props;
  const classes = useStyles(props);
  return <CardContent className={classes.cardGrid} {...other} />;
}

class Board extends Component {

  constructor(props) {
    super(props);
    this.state = {
      timer: null,
      items : "{}",
      userId: "",
      userName: "",
      score: 0,
      token: "",
      goodId: 0,
      good: "",
      price: 0,
      num: 0,
      confirm: false,
      items:[]
    }
  }

  initPage() {
    this.setState({
      userId: localStorage.getItem("userId"),
      userName: localStorage.getItem("userName"),
      score: localStorage.getItem("score"),
      token: localStorage.getItem("token"),
    })
  }

  componentWillMount() {
    this.initPage()

    Event.addEvents(document, "keydown",this.handleKeyDown);
    // Event.addEvents(document, "keypress",this.handleKeyPress);
    if (!localStorage.getItem("token")){
      router.push("/")
    }
  }

  componentDidMount(){
    const self = this
    self.getItem(self)
    this.state.timer=setInterval(()=>{
      self.getItem(self)
    }, 10000)
  }

  componentWillUmount(){
    document.removeEventListener("keydown",this.handleKeyDown);
    document.removeEventListener("keypress",this.handleKeyPress);
    if(this.state.timer!= null) {
      clearInterval(this.state.timer);
    }
  }


  componentDidUpdate() {
    // this.ddd()
  }

  getItem(self) {
    // return self.ggg(self) //使用本地数据测试
    //这里获取购买物品清单
    GetAsync("goods", {"token": self.state.token, "action": "getGoodsInfo", "type": "swop"}, function(resp){
      if (typeof(resp["errMsg"]) === "undefined"){
        return
      }

      const { errMsg, info } = resp
      if( errMsg !== "" ){
        alert(errMsg)
        return
      }

      if (info){
        let state = {'items': info}
        if (resp.hasOwnProperty('integral')){
          state.integral = resp.integral
          localStorage.setItem("score", resp.integral)
        }
        self.setState(state)
      }
    })
  }

  swopGoods( goodId ){
    //这里实现下单购买
    const resp = Get("goods", {"token": this.state.token, "action": "swopGoods", "good": goodId})

    if (typeof(resp["errMsg"]) === "undefined"){
      alert(NetErrMsg)
      return
    }

    const { errMsg, good, integral, userId, userName } = resp
    if( errMsg !== "" ){
      alert(errMsg)
      return []
    }

    this.setState({ "score": integral })
    localStorage.setItem("score", integral)

    alert(`恭喜${this.state.userName}购买${good}成功，剩余积分为${integral}`)

  }

  edit = event => {
    var data = JSON.parse(this.state.items)
    data[event.target.name] = event.target.value

    this.setState({ items: JSON.stringify(data) });
  }

  clickItem = ( item ) => {
    const { good, id, price, count } = JSON.parse(item)
    this.setState({ "good": good, "goodId": id, "price": price, "num": count, "confirm": true })
  }

  clickImage = (item) => {
    const { good, id} = JSON.parse(item)
    window.location.href = id=="105" ?  'http://cdnimage.ortron.cn/umi/邮箱猪(需要验证码需要切ip,不方便勿兑).gif' : 'http://cdnimage.ortron.cn/umi/' + good + '.jpg'
  }

  clickSwop = () =>{
    if (this.state.goodId !== ""){
      console.log(this.state.goodId)
      this.swopGoods(this.state.goodId)  //有接口了用这个
      //this.setState({ "good": "", "goodId": 0, "price": 0, "num": 0 })
    }
    this.confirmed()
    this.getItem(this)
  }

  confirmed = () =>{
    this.setState({ "confirm": false })
  }

  logout = () =>{
    localStorage.removeItem("token")
    this.componentWillUmount()
    router.push("/")
  }

  handleKeyDown = (event) => {
    if (this.state.idle){
      return
    }

    if(event.key === 'F12' || event.keyCode === 'F12'){
      event.preventDefault()
      window.event.returnValue = false;
      return (false)
    }
  }

  handleKeyPress = (event) => {

  }

  ddd() {
    if (this.eTermRes){
      const scrollHeight = this.eTermRes.scrollHeight;
      const height = this.eTermRes.clientHeight;
      const maxScrollTop = scrollHeight - height;
      this.eTermRes.scrollTop = maxScrollTop > 0 ? maxScrollTop : 0;
    }
  }

  ggg = (self) => {
    if (!self.items){
      self.items = [
        {'id': 1, 'good': 'cool', 'price': 11, 'count': 2, 'pic': 'item1.png'},
        {'id': 2, 'good': 'coool', 'price': 22, 'count': 2, 'pic': 'item1.png'},
        {'id': 3, 'good': 'cooool', 'price': 33, 'count': 2, 'pic': 'item1.png'},
        {'id': 4, 'good': 'coooool', 'price': 44, 'count': 2, 'pic': 'item1.png'},
        {'id': 5, 'good': 'bool', 'price': 11, 'count': 2, 'pic': 'item1.png'},
        {'id': 6, 'good': 'boool', 'price': 22, 'count': 2, 'pic': 'item1.png'},
        {'id': 7, 'good': 'booool', 'price': 33, 'count': 2, 'pic': 'item1.png'},
        {'id': 8, 'good': 'boooool', 'price': 44, 'count': 2, 'pic': 'item1.png'},
      ]
    }
    const items = self.items

    //测试刷新
    for (let info of items){
      info.count++
    }
    console.log(items)

    self.setState({'items': items})
  }

  renderItems = () => {
     const data = this.state.items
    // console.log(data)
    // for (let info of data){
    //   //info.pic = 'https://source.unsplash.com/random'
    //   info.pic = picUrl + info.pic
    //   // info.pic = 'http://ortron.oss-cn-shanghai.aliyuncs.com/test.jpg'
    // }

    //const transed = transList(data, 7)  //7是一行有多少个物品

    if (data.length == 0){
       return (
         <Typography> 加载中，如果长时间没有物品说明登录过期，请注销后重新登录</Typography>
       )
    }

    const transed = data
    return (

      <MyCardGrid maxWidth="md">
        <Grid container spacing={4}>
          {transed.map(v =>

                <Grid item key={"item" + v.id.toString()} xs={12} sm={6} md={4}>
                  <MyCard>
                    <MyCardMedia
                      image={v.id=="105" ?  'http://cdnimage.ortron.cn/umi/邮箱猪(需要验证码需要切ip,不方便勿兑).gif' : 'http://cdnimage.ortron.cn/umi/' + v.good  + '.jpg@400w_400h_80Q.jpg' }
                      good={ v.good }
                      onClick={ () => this.clickImage( JSON.stringify(v) ) }
                    />
                    <div>
                      <Typography>
                        品名：{ v.good }
                      </Typography>
                      <Typography>
                        价格：{ v.price }
                      </Typography>
                      <Typography>
                        数量：{ v.count }
                      </Typography>
                    </div>
                    <CardActions>
                      <Button variant="contained" color="primary" onClick={ () => this.clickItem( JSON.stringify(v) ) }>
                      购买
                      </Button>
                    </CardActions>
                  </MyCard>
                </ Grid>
          )}
        </Grid>
      </MyCardGrid>
    )
  }

  auction(){
    this.componentWillUmount()
    router.push("/auction")
  }

  render() {
    const Item = this.renderItems
    const self = this

    function TransitionsModal() {
      const classes = useStyles();

      return (
        <div>
          <Modal
            aria-labelledby="transition-modal-title"
            aria-describedby="transition-modal-description"
            className={classes.modal}
            open={self.state.confirm}
            onClose={self.confirmed}
          >
              <div className={classes.paper}>
                <Typography style={Styles.info}>
                  确认以{self.state.price}积分的价格竞拍{self.state.good}吗？<br />
                  库存还有{self.state.num}，先到先得哦
                </Typography>
                <Button variant="contained" color="primary"
                        onClick={self.clickSwop}
                >
                  购买
                </Button>
              </div>
          </Modal>
        </div>
      );
    }

    return (
      <ThemeProvider theme={theme}>
      <React.Fragment>
        <CssBaseline />
        <AppBar position="relative">
          <Toolbar>
            <Typography variant="h6" color="inherit" noWrap>
              购买物品
            </Typography>
            <Button variant="contained" color="primary" onClick={ () => this.auction() }>
              切换到拍卖
            </Button>
            <Button variant="contained" color="primary" onClick={ () => this.logout() }>
              注销
            </Button>
          </Toolbar>
        </AppBar>
        <main>
      <div>

        <Card>
          <Typography>
          用户：{this.state.userName} 积分：{this.state.score}
          </Typography>
        </Card>



          <Item />


      </div>
          <TransitionsModal/>
        </main>

      </React.Fragment>
      </ThemeProvider>
    )
  };
}

export default Board;
